from common.mysql_operate import db
from model.User import User
import ulid

class UserStore():
    def save(self, user):
        sql = "INSERT INTO user(username, password, email, number,create_time) " \
               "VALUES( '{}', '{}','{}','{}','{}')".format(user.username, user.password, user.email,
                                                                  ulid.new(), user.create_time)
        print(sql)
        db.execute_db(sql)

    def list(self):
        # 静态方法，生成查询所有用户的 SQL 语句
        sql = "SELECT * FROM user"
        return db.select_db(sql)

    def delete_by_number(self, number):
        sql = "DELETE FROM user WHERE number = '{}'".format(number)
        db.execute_db(sql)

    def update_by_number(self, user):
        sql_builder = ""
        if user.username != "":
            sql_builder += " username = '{}',".format(user.username)
        if user.password != "":
            sql_builder += " password = '{}',".format(user.password)
        if user.email != "":
            sql_builder += " email = '{}',".format(user.email)

        if sql_builder != "":
            sql_builder = "UPDATE user SET {} WHERE number = '{}'".format(sql_builder[:len(sql_builder) - 1],
                                                                             user.number)
        print(sql_builder)
        db.execute_db(sql_builder)

    def findUserByPasswordAndUsername(self, username, password):
        sql = "SELECT * FROM user WHERE username = '{}' and password = '{}'".format(username, password)
        return db.select_db(sql)

    def queryByNumber(self,number):
        sql = "SELECT * FROM user where number = '{}'".format(number)
        return db.select_db(sql)